// 增强版日志可视化系统
class LogsEnhanced {
    constructor() {
        this.charts = new Map();
        this.currentTimeRange = 'day';
        this.init();
    }

    // 初始化系统
    init() {
        this.initCharts();
        this.setupEventListeners();
        this.loadRealTimeData();
    }

    // 初始化图表
    initCharts() {
        // 日志类型分布图
        this.charts.set('logType', echarts.init(document.getElementById('logTypeChart')));
        
        // 24小时访问趋势图
        this.charts.set('hourlyTrend', echarts.init(document.getElementById('hourlyTrendChart')));
        
        // 操作状态分布图
        this.charts.set('status', echarts.init(document.getElementById('statusChart')));
        
        // 地理分布热力图
        this.charts.set('geo', echarts.init(document.getElementById('geoChart')));
        
        // 设备类型分布图
        this.charts.set('device', echarts.init(document.getElementById('deviceChart')));
        
        // 错误趋势分析图
        this.charts.set('errorTrend', echarts.init(document.getElementById('errorTrendChart')));

        // 响应式调整
        window.addEventListener('resize', () => {
            this.charts.forEach(chart => chart.resize());
        });

        // 初始加载数据
        this.loadChartData();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 时间范围切换
        document.querySelectorAll('.chart-filter').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const range = e.target.textContent === '今日' ? 'day' :
                            e.target.textContent === '本周' ? 'week' :
                            e.target.textContent === '本月' ? 'month' : 'year';
                this.setTimeRange(range, e.target);
            });
        });

        // 图表交互事件
        this.setupChartInteractions();
    }

    // 设置图表交互
    setupChartInteractions() {
        // 点击图表联动筛选
        this.charts.forEach((chart, key) => {
            chart.on('click', (params) => {
                this.handleChartClick(key, params);
            });
        });
    }

    // 处理图表点击事件
    handleChartClick(chartType, params) {
        switch (chartType) {
            case 'logType':
                this.filterByLogType(params.name);
                break;
            case 'status':
                this.filterByStatus(params.name);
                break;
            case 'geo':
                this.filterByCountry(params.name);
                break;
            case 'device':
                this.filterByDevice(params.name);
                break;
        }
    }

    // 设置时间范围
    setTimeRange(range, element) {
        this.currentTimeRange = range;
        
        // 更新按钮状态
        document.querySelectorAll('.chart-filter').forEach(btn => {
            btn.classList.remove('active');
        });
        element.classList.add('active');
        
        // 重新加载数据
        this.loadChartData();
    }

    // 加载图表数据
    async loadChartData() {
        try {
            const data = await this.fetchAnalyticsData();
            this.updateAllCharts(data);
        } catch (error) {
            console.error('加载图表数据失败:', error);
            this.showError('加载图表数据失败');
        }
    }

    // 获取分析数据
    async fetchAnalyticsData() {
        const response = await fetch(`/api/logs/analytics?range=${this.currentTimeRange}`);
        if (!response.ok) {
            throw new Error('获取分析数据失败');
        }
        return await response.json();
    }

    // 更新所有图表
    updateAllCharts(data) {
        this.updateLogTypeChart(data.typeDistribution);
        this.updateHourlyTrendChart(data.hourlyTrend);
        this.updateStatusChart(data.statusDistribution);
        this.updateGeoChart(data.geoDistribution);
        this.updateDeviceChart(data.deviceDistribution);
        this.updateErrorTrendChart(data.errorTrend);
    }

    // 更新日志类型分布图
    updateLogTypeChart(data) {
        const chart = this.charts.get('logType');
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: data.map(item => item.name)
            },
            series: [{
                name: '日志类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }]
        };
        chart.setOption(option);
    }

    // 更新24小时访问趋势图
    updateHourlyTrendChart(data) {
        const chart = this.charts.get('hourlyTrend');
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: Array.from({length: 24}, (_, i) => `${i}:00`)
            },
            yAxis: {
                type: 'value',
                name: '访问量'
            },
            series: [{
                name: '访问量',
                type: 'line',
                data: data,
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#3498db'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0, y: 0, x2: 0, y2: 1,
                        colorStops: [
                            {offset: 0, color: 'rgba(52, 152, 219, 0.3)'},
                            {offset: 1, color: 'rgba(52, 152, 219, 0.1)'}
                        ]
                    }
                },
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            }]
        };
        chart.setOption(option);
    }

    // 更新状态分布图
    updateStatusChart(data) {
        const chart = this.charts.get('status');
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 'right',
                data: data.map(item => item.name)
            },
            series: [{
                name: '操作状态',
                type: 'pie',
                radius: '70%',
                center: ['50%', '50%'],
                data: data,
                itemStyle: {
                    color: function(params) {
                        const colorList = ['#52c41a', '#faad14', '#f5222d'];
                        return colorList[params.dataIndex] || '#999';
                    }
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        };
        chart.setOption(option);
    }

    // 更新地理分布热力图
    updateGeoChart(data) {
        const chart = this.charts.get('geo');
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}'
            },
            visualMap: {
                min: 0,
                max: Math.max(...data.map(item => item.value)),
                text: ['高', '低'],
                calculable: true,
                inRange: {
                    color: ['#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027']
                }
            },
            series: [{
                name: '访问分布',
                type: 'map',
                map: 'world',
                roam: true,
                emphasis: {
                    label: {
                        show: true
                    }
                },
                data: data
            }]
        };
        chart.setOption(option);
    }

    // 更新设备类型分布图
    updateDeviceChart(data) {
        const chart = this.charts.get('device');
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value'
            },
            yAxis: {
                type: 'category',
                data: data.map(item => item.name)
            },
            series: [{
                name: '设备数量',
                type: 'bar',
                data: data.map(item => item.value),
                itemStyle: {
                    color: function(params) {
                        const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
                        return colorList[params.dataIndex % colorList.length];
                    }
                }
            }]
        };
        chart.setOption(option);
    }

    // 更新错误趋势分析图
    updateErrorTrendChart(data) {
        const chart = this.charts.get('errorTrend');
        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['错误数量', '警告数量', '成功数量']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.dates
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '错误数量',
                    type: 'line',
                    stack: '总量',
                    data: data.errors,
                    lineStyle: {
                        color: '#f5222d'
                    },
                    areaStyle: {
                        color: 'rgba(245, 34, 45, 0.1)'
                    }
                },
                {
                    name: '警告数量',
                    type: 'line',
                    stack: '总量',
                    data: data.warnings,
                    lineStyle: {
                        color: '#faad14'
                    },
                    areaStyle: {
                        color: 'rgba(250, 173, 20, 0.1)'
                    }
                },
                {
                    name: '成功数量',
                    type: 'line',
                    stack: '总量',
                    data: data.successes,
                    lineStyle: {
                        color: '#52c41a'
                    },
                    areaStyle: {
                        color: 'rgba(82, 196, 26, 0.1)'
                    }
                }
            ]
        };
        chart.setOption(option);
    }

    // 筛选功能
    filterByLogType(type) {
        document.getElementById('logType').value = type.toLowerCase();
        if (window.logSystem) {
            window.logSystem.searchLogs();
        }
    }

    filterByStatus(status) {
        // 在实际应用中，这里可以添加状态筛选逻辑
        console.log('筛选状态:', status);
    }

    filterByCountry(country) {
        document.getElementById('country').value = country;
        if (window.logSystem) {
            window.logSystem.searchLogs();
        }
    }

    filterByDevice(device) {
        // 在实际应用中，这里可以添加设备筛选逻辑
        console.log('筛选设备:', device);
    }

    // 实时数据加载
    loadRealTimeData() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.loadChartData();
        }, 30000);
    }

    // 显示错误消息
    showError(message) {
        const alert = document.createElement('div');
        alert.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            z-index: 10000;
            font-weight: bold;
            background: #e74c3c;
        `;
        alert.textContent = message;
        
        document.body.appendChild(alert);
        
        setTimeout(() => {
            document.body.removeChild(alert);
        }, 3000);
    }

    // 销毁图表
    destroy() {
        this.charts.forEach(chart => {
            chart.dispose();
        });
    }
}

// 全局函数
function setChartTimeRange(range) {
    const ranges = {
        'day': '今日',
        'week': '本周',
        'month': '本月',
        'year': '全年'
    };
    
    const buttonText = ranges[range];
    const button = Array.from(document.querySelectorAll('.chart-filter')).find(btn => btn.textContent === buttonText);
    
    if (button && window.logsEnhanced) {
        window.logsEnhanced.setTimeRange(range, button);
    }
}

// 页面加载完成后初始化
let logsEnhanced;
document.addEventListener('DOMContentLoaded', function() {
    logsEnhanced = new LogsEnhanced();
    window.logsEnhanced = logsEnhanced;
});